package com.projectName.www.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import k1.druid;
import org.jetbrains.annotations.Nullable;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JdbcUtils  {
    private static DataSource d=null;//连接池对象
    private static ThreadLocal<Connection>tl=new ThreadLocal<>();
    static {
        //初始化对象
        Properties p=new Properties();
        InputStream r = druid.class.getClassLoader().getResourceAsStream("com/projectName/www/config/druid.properties");
        try {
            p.load(r);
        } catch (IOException e) {
            throw new RuntimeException(e);

        }

        try {
            d = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
    //对外提供连接

    public static @Nullable Connection getConnection() throws Exception {
        //线程本地变量中是否存在
        Connection c = tl.get();
        if(c==null){
        c= d.getConnection();
        tl.set(c);
    }
    return  c;
    }
    public static void closeConnection() throws Exception {

        Connection connection = tl.get();
        if(connection!=null){
            tl.remove();//清空本地变量
            connection.setAutoCommit(true);//事务状态回归
            connection.close();//回收连接池
        }

    }

}
